package com.huodongrili.calender.bg;

import java.util.Calendar;
import java.util.Date;

import com.huodongrili.calender.BuildConfig;
import com.huodongrili.calender.R;
import com.huodongrili.calender.data.Constant;
import com.huodongrili.calender.data.DataPreferences;
import com.huodongrili.calender.model.WeatherInfo;
import com.huodongrili.calender.model.WeatherInfo.EWEATHER;
import com.huodongrili.calender.network.WeatherOper;
import com.huodongrili.calender.util.ECLog;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

public class LoadWeatherTask extends AsyncTask<Void, Void, WeatherInfo> {
	
	private Context mContext;
	
	public LoadWeatherTask(Context context){
		mContext = context;
	}

	@Override
	protected WeatherInfo doInBackground(Void... params) {
		WeatherOper wOper = new WeatherOper(mContext);

		return wOper.LoadWeatherData();
	}
	
	@Override
	protected void onPostExecute(WeatherInfo result) {
	
		if(BuildConfig.DEBUG){
			ECLog.debug("the load weather is over....");
		}
		
		Intent i = new Intent(Constant.ACTION_WEATHER_REFRESH);
		
		DataPreferences dpf = DataPreferences.getInstance(mContext);
		
		if(result !=null){
			
			 String temp = result.getTemperature();
			
			if(BuildConfig.DEBUG){
				ECLog.debug("the load weather WeatherInfo"+result.toString());
				ECLog.debug("the load weather status code:"+Constant.WEATHER_OK + ", temputer:"+temp);
			}
			
			
			EWEATHER ew = result.getStauts();
			
			int iconId = R.drawable.weather_sun;
			
			if(ew== EWEATHER.SNOW){
				iconId = R.drawable.weather_snow;
			}else if(ew==EWEATHER.RAIN){
				iconId = R.drawable.weather_rain;
			}else if(ew==EWEATHER.WIND){
				iconId = R.drawable.weather_wind;
			}else if(ew==EWEATHER.CLOUD){
				iconId = R.drawable.weather_cloud;
			}else{
				iconId = R.drawable.weather_sun;
			}
			
			
			dpf.setTemperature(temp);
			dpf.setWeatherIcon(iconId);
			
			
			i.putExtra(Constant.WEATHER_STATUS, Constant.WEATHER_OK);
			i.putExtra(Constant.WEATHER_ICON,iconId);
			i.putExtra(Constant.WEATHER_TEMP,temp);
			mContext.sendBroadcast(i);
		}else{
			
			if(BuildConfig.DEBUG){
				ECLog.debug("the load weather status code:"+Constant.WEATHER_ERROR);
			}
			
			if(!dpf.getLoadWeatherTime()){
				dpf.setTemperature("");
				dpf.setWeatherIcon(-1);
				
				i.putExtra(Constant.WEATHER_STATUS, Constant.WEATHER_ERROR);
				mContext.sendBroadcast(i);
			}

		}
		
		dpf.setLoadWeatherTime();

		
	}

}
